const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  // 代理所有以/api开头的请求到后端服务器
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:8080',
      changeOrigin: true,
      logLevel: 'debug',
      pathRewrite: {
        '^/api': '/vehicle-secure/api'
      },
      onProxyReq: (proxyReq, req, res) => {
        console.log(`Proxying ${req.method} request to: ${proxyReq.path}`);
        if (req.headers.authorization) {
          proxyReq.setHeader('Authorization', req.headers.authorization);
        }
      },
      onError: (err, req, res) => {
        console.error('Proxy error:', err);
      }
    })
  );
  
  // 代理所有以/vehicle-secure开头的请求到后端服务器
  // 解决其他页面API请求问题
  app.use(
    '/vehicle-secure',
    createProxyMiddleware({
      target: 'http://localhost:8080',
      changeOrigin: true,
      logLevel: 'debug',
      // 不修改路径，直接转发
      pathRewrite: {
        '^/vehicle-secure': '/vehicle-secure'
      },
      onProxyReq: (proxyReq, req, res) => {
        console.log(`Proxying ${req.method} request to: ${proxyReq.path}`);
        if (req.headers.authorization) {
          proxyReq.setHeader('Authorization', req.headers.authorization);
        }
      },
      onError: (err, req, res) => {
        console.error('Proxy error:', err);
      }
    })
  );
};